package com.hzz.framework.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

@Slf4j
public class IpUtil {
    /**
     * 校验所给IP是否满足给定规则
     *
     * @param ipStr     待校验IP
     * @param ipPattern IP匹配规则。支持 * 匹配所有和 - 匹配范围。用分号分隔 &lt;br&gt;
     *                  例如：10.34.163.*,10.34.162.1 -128
     * @return
     * @author li_hongzhe @nhn.com
     * @date 2014年10月23日 下午1:38:37
     */
    public static boolean validateIP(String ipStr, String ipPattern) {
        if (ipStr == null || ipPattern == null) {
            return false;
        }
        String[] patternList = ipPattern.split(",");
        for (String pattern : patternList) {
            if (passValidate(ipStr, pattern)) {
                return true;
            }
        }
        return false;
    }

    private static boolean passValidate(String ipStr, String pattern) {
        String[] ipStrArr = ipStr.split("\\.");
        String[] patternArr = pattern.split("\\.");
//        if ( ipStrArr. length != 4 || patternArr. length != 4) {
//            return false;
//        }
        int end = ipStrArr.length;
        int patternLength = patternArr.length;
        if (patternLength == 4 && patternArr[3].contains("-")) {
            end = 3;
            String[] rangeArr = patternArr[3].split("-");
            int from = Integer.valueOf(rangeArr[0]).intValue();
            int to = Integer.valueOf(rangeArr[1]).intValue();
            int value = Integer.valueOf(ipStrArr[3]).intValue();
            if (value < from || value > to) {
                return false;
            }
        }
        for (int i = 0; i < end; i++) {
            if ("*".equals(patternArr[i])) {
                continue;
            }
            if (!patternArr[i].equalsIgnoreCase(ipStrArr[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取访问者IP
     * <p>
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     * <p>
     * 本方法先从Header中获取Proxy-Client-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("Proxy-Client-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("WL-Proxy-Client-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    public static String getMACAddress(String ip) {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    //if (str.indexOf("MAC Address") > 1) {
                    if (str.indexOf("MAC") > 1) {
                        macAddress = str.substring(
                                str.indexOf("=") + 2);
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }
}
